import cs from 'classnames';
import { Dayjs } from "dayjs";
import { CSSProperties, ReactNode, useContext } from "react";
import allLocales from "./Calendar/locale/index";
import LocaleContext from "./Calendar/localeContext.tsx";

interface CalendarProps {
  value: Dayjs;
  locale?: string;
  className?: string | string[];
  style?: CSSProperties;
  onChange?: (day: Dayjs) => void;
  dateRender?: (currentDate: Dayjs) => ReactNode;
  dateInnerContent?: (currentDate: Dayjs) => ReactNode;
}

interface MonthCalendarProps extends CalendarProps {}

function getAllDays(date: Dayjs) {
  const daysInMonth = date.daysInMonth(); // 这个月有多少天
  const startDate = date.startOf("month");
  const day = startDate.day();

  const daysInfo: { currentMonth: boolean; date: Dayjs }[] = new Array(6 * 7);

  for (let i = 0; i < day; i++) {
    daysInfo[i] = {
      date: startDate.subtract(day - i, "day"),
      currentMonth: false,
    };
  }

  for (let i = day; i < daysInfo.length; i++) {
    const calcDate = startDate.add(i - day, "day");
    daysInfo[i] = {
      date: calcDate,
      currentMonth: calcDate.month() === date.month(),
    };
  }
  return daysInfo;
}

function renderDays(
  days: Array<{ currentMonth: boolean; date: Dayjs }>,
  dateRender: MonthCalendarProps["dateRender"],
  dateInnerContent: MonthCalendarProps["dateInnerContent"],
  value: Dayjs
) {
  const rows = [];
  for (let i = 0; i < 6; i++) {
    const row = [];
    for (let j = 0; j < 7; j++) {
      const item = days[i * 7 + j];
      row[j] = (
        <div
          key={`row-${i}-${j}`}
          className={
            "calendar-month-body-cell" +
            (item.currentMonth ? " calendar-month-body-cell-current" : "")
          }
        >
          {dateRender ? (
            dateRender(item.date)
          ) : (
            <div className="calendar-month-body-cell-date">
              <div className="calendar-month-body-cell-date-value">
                {item.date.date()}
              </div>
              <div className={
                cs("calendar-month-body-cell-date-content", value.format('YYYY-MM-DD') === item.date.format('YYYY-MM-DD')
                ? 'calendar-month-body-cell-date-selected' : ''
                ) 
              }>
                {dateInnerContent?.(item.date)}
              </div>
            </div>
          )}
        </div>
      );
    }
    rows.push(row);
  }
  return rows.map((row, index) => (
    <div key={`row-${index}`} className="calendar-month-body-row">
      {row}
    </div>
  ));
}

export const MonthCalender = function (props: MonthCalendarProps) {
  const localeContext = useContext(LocaleContext);
  const CalendarLocale = allLocales[localeContext.locale];
  const { value, dateRender, dateInnerContent } = props;

  const weekList = [
    "sunday",
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday",
  ];
  const allDays = getAllDays(props.value);
  return (
    <div className="calendar-month">
      <div className="calendar-month-week-list">
        {weekList.map((week, index) => {
          return (
            <div
              key={`title-${week}`}
              className="calendar-month-week-list-item"
            >
              {CalendarLocale.week[week]}
            </div>
          );
        })}
      </div>
      <div className="calendar-month-body">
        {renderDays(allDays, dateRender, dateInnerContent, value)}
      </div>
    </div>
  );
};
